<template>
  <h3 style="color: skyblue" v-if="props.familySize > 0">添加{{ props.familySize }}位家庭成员</h3>
  <h3 style="color: red" v-else>没有家庭成员不用添加</h3>
  <el-form
    ref="hzFamilyNumberFromRef"
    :model="dynamicValidateForm"
    label-width="120px"
    class="demo-dynamic"
    :rules="rules"
  >
    <!--持续添加的内容    -->
    <el-row :gutter="24">
      <el-col :span="20">
      </el-col>
      <el-col :span="4">
        <el-button @click.prevent="addDomain()">
          <el-icon>
            <Plus />
          </el-icon>
          点击此处进行添加
        </el-button>
      </el-col>
    </el-row>
    <template v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key">
      <el-divider content-position="left"><span class="el-divider-h4">  {{ "家庭成员&nbsp;&nbsp;&nbsp;" + (index + 1)
        }}</span></el-divider>
      <el-row :gutter="24">
        <el-col :span="10">
          <el-form-item
            label="姓名"
            :prop="'domains.' + index + '.famName'"
            :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]"
          >
            <el-input v-model="domain.famName"  maxlength="50" show-word-limit placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            label="身份证号"
            :prop="'domains.' + index + '.famIdCardNum'"
            :rules="[
              { required: true, message: '请输入户主的身份证号', trigger: 'blur' },
              { validator: validateIdCardNumber, trigger: 'blur' },
            ]"
          >
            <el-input v-model="domain.famIdCardNum" placeholder="请输入身份证号" show-word-limit maxlength="18" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="10">
          <el-form-item
            label="与户主的关系"
            :prop="'domains.' + index + '.famRelationShip'"
            :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
          >
            <el-select
              v-model="domain.famRelationShip"
              placeholder="请选择与户主的关系"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in dict.type.hz_relation_ship"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            label="劳动力状况"
            :prop="'domains.' + index + '.famLaborCondition'"
            :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
          >
            <el-select
              v-model="domain.famLaborCondition"
              placeholder="请选择与劳动力状况"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in dict.type.labor_status"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button @click.prevent="removeDomain(domain)">
            <el-icon>
              <Minus />
            </el-icon>
          </el-button>
        </el-col>
      </el-row>
    </template>
    <el-form-item v-if="dynamicValidateForm.domains.length > 0">
      <el-button @click="resetForm(hzFamilyNumberFromRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref, watch } from "vue";
import type { FormInstance } from "element-plus";
import { Minus, Plus } from "@element-plus/icons-vue";
import { FormRules } from "element-plus";
import { validateIdCardNumber, validatorMethod, verifyPhone } from "@/utils/validate";

const hzFamilyNumberFromRef = ref<FormInstance>();
const { proxy }: any = getCurrentInstance();

/*要提交的表单信息*/
interface DomainItem {
  key: number;
  famId: number;
  hzId: number;
  famName: string;
  famIdCardNum: string;
  famRelationShip: string;
  famLaborCondition: string; //劳动力状况
}

let props = defineProps(["peaHzFamList", "familySize", "hzId"]);
let $emit = defineEmits(["update:peaHzFamList", "update:familySize"]);


watch(
  () => props.familySize,
  () => {
    // 先进行清除
    if (props.hzId === "") {
      if (props.familySize > dynamicValidateForm.domains.length) {
        // 进行添加
        let len = props.familySize - dynamicValidateForm.domains.length;
        for (let i = 0; i < len; i++) {
          addDomain();
        }
      }
      if (props.familySize < dynamicValidateForm.domains.length) {
        //进行删除
        let len = dynamicValidateForm.domains.length - props.familySize;
        for (let i = 0; i < len; i++) {
          dynamicValidateForm.domains.pop();
        }
      }
    }
  }
);

watch(
  () => props.hzId,
  () => {
    if (props.peaHzFamList.length > 0) {
      for (let creHzFam of props.peaHzFamList) {
        dynamicValidateForm.domains.push({
          key: Date.now(),
          famId: creHzFam.famId,
          hzId: creHzFam.hzId,
          famName: creHzFam.famName,
          famIdCardNum: creHzFam.famIdCardNum,
          famRelationShip: creHzFam.famRelationShip,
          famLaborCondition: creHzFam.famLaborCondition
        });
      }
    }
  }
);

onMounted(() => {
  $emit("update:peaHzFamList", dynamicValidateForm.domains);
  if (props.peaHzFamList.length > 0) {
    for (let creHzFam of props.peaHzFamList) {
      dynamicValidateForm.domains.push({
        key: Date.now(),
        famId: creHzFam.famId,
        hzId: creHzFam.hzId,
        famName: creHzFam.famName,
        famIdCardNum: creHzFam.famIdCardNum,
        famRelationShip: creHzFam.famRelationShip,
        famLaborCondition: creHzFam.famLaborCondition
      });
    }
  }
  if (props.familySize > dynamicValidateForm.domains.length) {
    // 进行添加
    let len = props.familySize - dynamicValidateForm.domains.length;
    for (let i = 0; i < parseInt(len); i++) {
      addDomain();
    }
  }
});

const dynamicValidateForm = reactive<{
  domains: DomainItem[]
}>({
  domains: []
});

const removeDomain = (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1);
    $emit("update:peaHzFamList", dynamicValidateForm.domains);
  }
};

// 进行添加操作
const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    famId: "",
    hzId: "",
    famName: "",
    idCardNum: "",
    hzRelationShip: "",
    laborCondition: ""
  });
  $emit("update:peaHzFamList", dynamicValidateForm.domains);
};


// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 验证规则
const rules = reactive<FormRules>({
  famName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  idCardNumber: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    { validator: validateIdCardNumber, trigger: "blur" }
  ],
})

// 进行表单校验
const submitHzFamNumForm = async () => {
  // 创建一个 Promise 对象
  return new Promise((resolve, reject) => {
    if (props.familySize != dynamicValidateForm.domains.length) {
      reject("请检查家庭成员人数是否与添加的个数相同！");
    }
    if (!hzFamilyNumberFromRef) {
      reject("仔细检查，还有未填写字段！");
    }
    hzFamilyNumberFromRef.value.validate((valid, fields) => {
      if (valid) {
        resolve(true);
      } else {
        console.log("error submit!", fields);
        reject("表单还有未填写字段，请填写！");
      }
    });
  });
};

defineExpose({
  submitHzFamNumForm
});
</script>

<script lang="ts">
export default {
  dicts: ["hz_relation_ship", "labor_status"],
  name: "hzFamilyNumberFrom"
};
</script>

<style lang="scss" scoped>
.el-form {
  font-weight: bold;
}

.el-divider-h4 {
  font-size: 15px;
  color: #00e4ff;
  font-weight: bold;
}
</style>
